<?php
/**
 *	  商户管理列表数据层
 *	  by Ouyoung
 *
 */
class supplier_table extends table {
    protected $result = array();
	protected $_validate = array(
        array('company','','{supplier/supplier_company_exist}',0,'unique',1),
        array('supplier_name','','{supplier/supplier_company_exist}',0,'unique',1),
		array('company', 'require', '{supplier/supplier_compay_require}', table::MUST_VALIDATE),
        array('supplier_name', 'require', '{supplier/supplier_name_require}', table::MUST_VALIDATE), 
		array('recommender', 'require', '{supplier/supplier_recommender_require}', table::MUST_VALIDATE),
        array('status','number','{supplier/state_require}',table::EXISTS_VALIDATE,'regex',table:: MODEL_BOTH),
	);
    
	protected $_auto = array(
		//array('status ','1'),
        array('recommender_id','0'),//推荐人ID默认填充
		array('updata_time', 'strtotime', 3, 'function'),
	);
    
    public function status($status){
        if(is_null($status)){
            return $this;
        }
        $this->where(array('status'=>$status));
        return $this;
    }
    
   	public function keyword($keyword){
        if(!$keyword){
            return $this;
        }
        $this->where(array('company'=>array('LIKE','%'.$keyword.'%')));
        return $this;
    }
    
    public function detail($id,$field = TRUE){
        if($id < 1){
            return $this;
        } 
        $this->result['supplier'] = $this->field($field)->find($id);
        return $this;
    }
    
    public function output(){
        return $this->result['supplier'];
    }
    
	protected function _after_find(&$result, $options) {
		$group = $this->load->table('supplier_group')->where(array('id' => $result['group_id']))->find();
        // var_dump($group);die;
        $result['group_title'] = isset($group['title']) ?  $group['title'] : '--';
		$result['updata_time'] = date('Y-m-d H:i:s', $result['updata_time']);
		return $result;
	}

	protected function _after_select(&$result, $options) {
		foreach ($result as &$record) {
			$this->_after_find($record, $options);
		}
		return $result;
	}

	public function fetch_by_company($company) {
		return $this->where(array("company" => $company))->find();
	}
    
	public function fetch_by_id($id) {
		return $this->where(array("id" => $id))->find();
	}
}